package com.hsj.mqconsumer.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 可重入队列消费者
 * @author:Teacher黄
 * @date:Created at 2020/01/05
 */
@Component
public class RecoverConsumer {

    private Integer num = 0;

    /**
     * 消费者01
     * @param msg
     * @param headers
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "recover_queue",durable = "true",autoDelete = "false"),
            exchange = @Exchange(name = "recover_exchange"),
            key = "recover"
    ))
    @RabbitHandler
    public void recover(String msg, @Headers Map<String,Object> headers, Channel channel) throws IOException {
        long deliveryTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        if(num <= 10){
            System.out.println("消费者01-接收到消息-可重入队列-不同消费者:"+msg);
            channel.basicRecover(true);
            num++;
        }else{
            if(num >= 20){
                // 确认消费
                channel.basicAck(deliveryTag,true);
                return;
            }

            System.out.println("消费者01-接收到消息-可重入队列-相同消费者:"+msg);
            channel.basicRecover(true);
            num++;
        }
    }


    /**
     * 消费者02
     * @param msg
     * @param headers
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "recover_queue",durable = "true",autoDelete = "false"),
            exchange = @Exchange(name = "recover_exchange"),
            key = "recover"
    ))
    @RabbitHandler
    public void recover02(String msg, @Headers Map<String,Object> headers, Channel channel) throws IOException {
        long deliveryTag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
        if(num <= 10){
            System.out.println("消费者02-接收到消息-可重入队列-不同消费者:"+msg);
            channel.basicRecover(true);
            num++;
        }else{
            if(num >= 20){
                // 确认消费
                channel.basicAck(deliveryTag,true);
                return;
            }

            System.out.println("消费者02-接收到消息-可重入队列-相同消费者:"+msg);
            channel.basicRecover(true);
            num++;
        }
    }


}
